package com.tencent.qplus.paddata.stat;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.tencent.qplus.paddata.db.DataSourceManager;
import com.tencent.qplus.paddata.util.ConfigUtil;
import com.tencent.qplus.paddata.util.JdbcUtils;


/**
 * 解析日志将用户信息归总
 * @author shiangzhang
 *
 * 2012-1-4
 */
public class ParseLogFileJob2 extends Job{
	
	private static String logFilePath = ConfigUtil.getString("logfile_path");
	private static Pattern logLinePattern = Pattern.compile("^\\[\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}\\]");
	
	private static Connection conn;
	
	private Logger logger = Logger.getLogger(ParseLogFileJob2.class);
	private Set<Long> logDatas = new HashSet<Long>();
	
	
	@Override
	public void init() {
		try {
			conn = DataSourceManager.getInstance().getDataSource("paddatadb").getConnection();
		} catch (SQLException e) {
			logger.error(e);
			e.printStackTrace();
		}
	}
	
	public void uninit(){
		JdbcUtils.release(conn);
	}
	
	private File[] getLogFiles(final String statDate){
		File path = new File(logFilePath);
		FileFilter filter = new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				if(pathname.isFile()){
					String fileName = pathname.getName();
					if(fileName.startsWith("msg-") && fileName.endsWith(".log."+statDate))
						return true;
				}
				return false;
			}
		};
		return path.listFiles(filter);
	}
	
	private void parseFile(String statDate,File logFile){
		try {
			BufferedReader br = new BufferedReader(new FileReader(logFile));
			String line=null;
			int lineNum = 0;
			int versionLineNum = 0;
			
			while((line = br.readLine())!=null){
				try{
					lineNum++;
					if(line.indexOf("version=")>0 && logLinePattern.matcher(line).find()){
					    int begin = line.indexOf("=")+1;
					    String versionStr = line.substring(begin);
					    String[] ss = versionStr.split("\\|");
					    if(ss.length!=2 || "100".equals(ss[1]))continue;
					    Long uin = Long.valueOf(ss[1]);
					    logDatas.add(uin);
				    }
				}catch (Exception e) {
					logger.error(e);
				}
			}
			logger.info("Fils:<<"+logFile.getName()+">>totalLine:"+lineNum+"versionLine:"+versionLineNum);
		} catch (FileNotFoundException e) {
			logger.error(e);
		} catch (IOException e) {
			logger.error(e);
		} 
	}
	
	public void insertIntoDb(){
		PreparedStatement pst = null;
		try {
			pst = conn.prepareStatement("INSERT INTO userdata_? (uin,firstlogindate)VALUE(?,?) ON DUPLICATE KEY UPDATE lastlogindate=?");
			pst.execute("use paduser");
		} catch (SQLException e) {
			logger.error(e);
		}
		int k = 0;
		for(int i=0;i<1000;i++){
			for(Long uin:logDatas){
				 long tableIndex = 0;
				    try{
				    	tableIndex = uin%1000;
				    	if(i==tableIndex){
				    		pst.setInt(1, i);
				    		pst.setLong(1, uin);
				    		pst.setString(3, this.statDate);
				    		pst.setString(4, this.statDate);
				    		pst.addBatch();
				    		if(++k%1000 ==0){
				    			pst.executeBatch();
				    		}
				    	}
				    }catch(Exception e){
				    	logger.error(e);
				    	continue;
				    }
			}
			try {
				pst.executeBatch();
			} catch (SQLException e) {
				logger.error(e);
			}
		}
		logDatas.clear();
	}
	
//version=12|270766733|0|1|240|854*480|8|5|477.28906MB| ARMv7 Processor rev 2 (v7l)|motorola MotoA953
	@Override
	public void run() {
		init();
		File[] logFiles = getLogFiles(statDate);
		for(File logFile:logFiles){
			parseFile(statDate, logFile);
		}
		insertIntoDb();
		uninit();
	}

	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//196.64516 | 191.69812
//		String s = calScreenSize("196.64516","191.69812","480*800");
//		System.out.println(s);
		ParseLogFileJob2 job = new ParseLogFileJob2();
		job.stat(args);
	}

	@Override
	public void stat(String[] args) {
		if(args!=null && args.length==1 && dateUtils.isDateStr(args[0])){
			this.statDate = args[0];
		}
		logger.info("start stat..................: "+statDate);
		run();
		logger.info("stat done..................: "+statDate);
	}
}
